package com.crcode.crm.service.log.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.crcode.crm.bean.log.DataLogBean;
import com.crcode.crm.dao.log.DataLogDao;
import com.crcode.crm.service.log.DataLogService;
import com.crcode.crm.utils.DateUtil;
import com.crcode.crm.utils.PageVo;
import com.crcode.crm.utils.ResultPageUtil;
import com.crcode.crm.utils.ResultUtil;

/**
 * 日志业务实现类
 *
 * @author lxw
 * @date 2019年4月9日
 */

@Service(value = "logService")
public class DataLogServiceImpl implements DataLogService {

    @Autowired
    private DataLogDao logDao;

    @Override
    public DataLogBean getById(Integer serializable) {

        return this.logDao.findById(serializable).get();
    }

    @Override
    public DataLogBean saveResultBean(DataLogBean t) {

        return this.logDao.save(t);
    }

    /**
     * 保存日志
     *
     * @param t
     * @return
     * @author lmz
     */
    @Override
    public boolean saveResultBoolean(DataLogBean t) {
        try {
            this.logDao.save(t);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     *
     *
     * @param t
     * @return
     * @author lmz
     */
    @Override
    public DataLogBean updateResultBean(DataLogBean t) {

        return this.logDao.save(t);
    }

    /**
     *
     *
     * @param t
     * @return
     * @author lmz
     */
    @Override
    public boolean updateResultBoolean(DataLogBean t) {

        try {
            this.logDao.save(t);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据id删除
     *
     * @param serializable
     * @return
     */
    @Override
    public boolean delete(Integer serializable) {

        try {
            this.logDao.deleteById(serializable);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @Override
    public List<DataLogBean> getAll() {

        return this.logDao.findAll();
    }

    /**
     * 根据条件分页加载
     *
     * @param param
     * @param vo
     * @return
     * @author lxw
     * @date 2018年4月1日 下午2:26:17
     */
    @Override
    public ResultPageUtil findBySpec(Map<String, Object> param, PageVo vo) {
        //System.out.println("limit=======>"+vo.getPageSize());
        Integer pageIndex = vo.getPageIndex() - 1;
        Pageable pageable = null;
        if (StringUtils.isNotEmpty(vo.getOrderBy())) {
            if (vo.getOrderDesc() == 1) {
                pageable = PageRequest.of(pageIndex, vo.getPageSize(), Direction.DESC, vo.getOrderBy());
            } else if (vo.getOrderDesc() == 0) {
                pageable = PageRequest.of(pageIndex, vo.getPageSize(), Direction.ASC, vo.getOrderBy());
            }
        } else {
            pageable = PageRequest.of(pageIndex, vo.getPageSize());
        }
        Page<DataLogBean> page = logDao.findAll(spec(param), pageable);
        ResultPageUtil ru = new ResultPageUtil();
        ru.setCurrentPage(vo.getPageIndex());
        ru.setPageSize(vo.getPageSize());
        ru.setTotalPages(page.getTotalPages());
        ru.setRows(page.getContent());
        ru.setTotal(page.getTotalElements());
        return ru;
    }


    /**
     * 创建动态查询语句
     *
     * @param params
     * @return
     */
    private Specification<DataLogBean> spec(final Map<String, Object> map) {
        Specification<DataLogBean> spec = new Specification<DataLogBean>() {

            private static final long serialVersionUID = 1L;
            @Override
            public Predicate toPredicate(Root<DataLogBean> root, CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                //System.out.println("开始时间"+params.get("startTime"));
                //对参数进行修改，转换成map
               // Map<String, Object> map = JSON.toJavaObject((JSON) JSONObject.parse((String) params.get("conditions")), Map.class);
                //System.out.println(map.get("searchWords"));

                // System.out.println("日志的类行：====》"+map.get("logType"));
                //日志类型 0、企业日志，1项目日志。默认为0
                System.out.println(JSON.toJSONString(map));
                if (map.get("logType") != null && map.get("logType") != "") {
                    predicates.add(cb.equal(root.get("logType"), map.get("logType")));
                }
                else {

                }
                if (map.get("detailedType") != null && map.get("detailedType") != "") {
                    predicates.add(cb.equal(root.get("detailedType"), map.get("detailedType")));
                }
                //创建时间检索
                if (map.get("startTime") != null && map.get("startTime") != "") {
                    //System.out.println(DateUtil.StrToDate(map.get("startTime").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
                    predicates.add(cb.greaterThanOrEqualTo(root.get("operateTime").as(Date.class), DateUtil.StrToDate(map.get("startTime").toString() + " 00:00:00", "yyyy-MM-dd HH:mm:ss")));
                    //predicates.add(cb.greaterThanOrEqualTo(root.get("operateTime"), map.get("startTime") + " 00:00:00"));
                }
                if (map.get("endtTime") != null && map.get("endtTime") != "") {
                    //System.out.println(DateUtil.StrToDate(map.get("endtTime").toString() + " 23:59:59", "yyyy-MM-dd HH:mm:ss"));
                    predicates.add(cb.lessThanOrEqualTo(root.get("operateTime").as(Date.class), DateUtil.StrToDate(map.get("endtTime").toString() + " 23:59:59", "yyyy-MM-dd HH:mm:ss")));
                    //predicates.add(cb.lessThanOrEqualTo(root.get("operateTime"), map.get("endtTime") + " 23:59:59"));
                }
                //根据用户UUID查询
                if (map.get("userUuid") != null && map.get("userUuid") != "" && !map.get("userUuid").equals("admin")) {
                    predicates.add(cb.equal(root.get("userUuid"), map.get("userUuid")));
                }
                //检索关键字
                if (map.get("searchWords") != null && map.get("searchWords") != "") {
                    predicates.add(cb.or(
                            cb.like(root.get("userName"), "%" + map.get("searchWords") + "%"),
                            cb.like(root.get("dataTuid"), "%" + map.get("searchWords") + "%"),
                            cb.like(root.get("dataTitle"), "%" + map.get("searchWords") + "%"),
                            cb.like(root.get("operateRemarks"), "%" + map.get("searchWords") + "%")
                    ));
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return spec;
    }


    /**
     * 根据id批量删除
     *
     * @param ids
     * @return
     * @author lmz
     */
    @Override
    public ResultUtil deleteLog(String ids) {
        return null;
    }

    /**
     * 根据id查询日志文件
     * @param id
     * @return
     */

    @Override
    public DataLogBean findLogByid(Integer id) {

        return logDao.findDataLogBeanById(id);
    }

    /**
     * 保存日志文件
     * @param logs
     * @return
     */
    @Override
    public boolean saveAllBoolean(List<DataLogBean> logs) {
        try {
            this.logDao.saveAll(logs);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
